﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Driver;

namespace FingerTip.Infrastructure.MongoDb
{
    public static class MongoDbExtensions
    {
        public static void Insert<T>(this IMongoDatabase database, T obj)
        {
            var collection = database.GetCollection<T>(nameof(T));
            collection.InsertOne(obj);
        }

        public static IEnumerable<T> Find<T>(this IMongoDatabase database, Expression<Func<T, bool>> filter)
        {
            var collection = database.GetCollection<T>(nameof(T));
            var result = collection.Find<T>(filter);
            return result?.ToList();
        }
        public static bool UpdateOne<T>(this IMongoDatabase database, Expression<Func<T, bool>> filter, UpdateDefinition<T> update)
        {
            var collection = database.GetCollection<T>(nameof(T));
            var result = collection.UpdateOne<T>(filter, update);
            return result.IsAcknowledged;
        }
        public static bool UpdateMany<T>(this IMongoDatabase database, Expression<Func<T, bool>> filter, UpdateDefinition<T> update)
        {
            var collection = database.GetCollection<T>(nameof(T));
            var result = collection.UpdateMany<T>(filter, update);
            return result.IsAcknowledged;
        }
        public static bool DeleteOne<T>(this IMongoDatabase database, Expression<Func<T, bool>> filter)
        {
            var collection = database.GetCollection<T>(nameof(T));
            var result = collection.DeleteOne<T>(filter);
            return true;
        }

        public static bool DeleteMany<T>(this IMongoDatabase database, Expression<Func<T, bool>> filter)
        {
            var collection = database.GetCollection<T>(nameof(T));
            var result = collection.DeleteMany<T>(filter);
            return true;
        }

        public static IMongoCollection<T> GetCollection<T>(this IMongoDatabase database)
        {
           return  database.GetCollection<T>(nameof(T));
        }
    }
}